package com.studyweb.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.studyweb.pojo.vo.Result;
import com.studyweb.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 登录检查拦截器
 * 
 * <p>统一处理JWT token验证，避免在每个Controller方法中重复验证</p>
 * 
 * @author StudyWeb Team
 * @since 1.0.0
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("LoginCheckInterceptor preHandle ...");
        
        // 1.获取请求url
        String url = request.getRequestURL().toString();
        log.info("请求的url: {}", url);
        
        // 2.判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if (url.contains("login") || url.contains("register")) {
            log.info("登录/注册操作，放行...");
            return true;
        }
        
        // 3.获取请求头中的令牌（token）
        String token = jwtUtils.getTokenFromRequest(request);
        
        // 4.判断令牌是否存在，如果不存在，返回错误结果（未登录）
        if (!StringUtils.hasLength(token)) {
            log.info("请求头token为空，返回未登录的信息");
            Result<String> error = Result.error("未登录或登录已过期");
            // 手动转换 对象->json
            String notLogin = JSONObject.toJSONString(error);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(notLogin);
            return false;
        }
        
        // 5.解析token，如果解析失败，返回错误结果（未登录）
        try {
            if (!jwtUtils.validateToken(token)) {
                log.info("token验证失败，返回未登录错误信息");
                Result<String> error = Result.error("未登录或登录已过期");
                String notLogin = JSONObject.toJSONString(error);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(notLogin);
                return false;
            }
            
            // 6.解析token获取用户ID，并存储到request attribute中
            Long userId = jwtUtils.getUserIdFromToken(token);
            request.setAttribute("userId", userId);
            log.info("token验证成功，用户ID: {}", userId);
            
        } catch (Exception e) {
            log.error("解析令牌失败: {}", e.getMessage());
            Result<String> error = Result.error("未登录或登录已过期");
            String notLogin = JSONObject.toJSONString(error);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(notLogin);
            return false;
        }
        
        // 7.放行
        log.info("令牌合法，放行");
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.debug("postHandle ...");
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.debug("afterCompletion ...");
    }
}